function varargout = config(varargin)
% CONFIG MATLAB code for config.fig
%      CONFIG, by itself, creates a new CONFIG or raises the existing
%      singleton*.
%
%      H = CONFIG returns the handle to a new CONFIG or the handle to
%      the existing singleton*.
%
%      CONFIG('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in CONFIG.M with the given input arguments.
%
%      CONFIG('Property','Value',...) creates a new CONFIG or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before config_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to config_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help config

% Last Modified by GUIDE v2.5 29-Apr-2014 21:34:11

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @config_OpeningFcn, ...
                   'gui_OutputFcn',  @config_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before config is made visible.
function config_OpeningFcn(hObject, ~, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to config (see VARARGIN)

% Check the existence of the configuration file
% ATTENTION: if you have self defined configuration files for your plugins,
% avoid using the filename 'rteegconfig.mat'
curFilePath = mfilename('fullpath');
curFolderPath = fileparts(curFilePath);
configFilePath = fullfile(curFolderPath, 'config/rteegconfig.mat');
handles.configFilePath = configFilePath;
if ~exist(configFilePath, 'file')
    genconfig(configFilePath);
end

% Load configuration from the production configuration file
loadconfig(configFilePath, hObject);

% Store some of the configuraion into the userdata of each control
% In case of any incorrupt the configuration, the old
% valid one will be used again.
fileStoragePath = get(handles.txtStoragePath, 'String');
set(handles.txtStoragePath, 'UserData', fileStoragePath);

realTimeWindowLength = get(handles.txtRealtimeWindowLength, 'String');
set(handles.txtRealtimeWindowLength, 'UserData', realTimeWindowLength);

scannerClockFrequency = get(handles.txtScannerClockFrequency, 'String');
set(handles.txtScannerClockFrequency, 'UserData', scannerClockFrequency);

syncMarkerUpdateInterval = get(handles.txtSyncMarkerUpdateInterval, 'String');
set(handles.txtSyncMarkerUpdateInterval, 'UserData', syncMarkerUpdateInterval);

movegui(hObject, 'center');

% Choose default command line output for config
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes config wait for user response (see UIRESUME)
uiwait(handles.figConfig);


% --- Outputs from this function are returned to the command line.
function varargout = config_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;

delete(hObject);


% --- Executes on selection change in popSamplingRate.
function popSamplingRate_Callback(hObject, eventdata, handles)
% hObject    handle to popSamplingRate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popSamplingRate contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popSamplingRate


% --- Executes during object creation, after setting all properties.
function popSamplingRate_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popSamplingRate (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in popSimulation.
function popSimulation_Callback(hObject, eventdata, handles)
% hObject    handle to popSimulation (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popSimulation contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popSimulation


% --- Executes during object creation, after setting all properties.
function popSimulation_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popSimulation (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function txtScannerClockFrequency_Callback(hObject, eventdata, handles)
% hObject    handle to txtScannerClockFrequency (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtScannerClockFrequency as text
%        str2double(get(hObject,'String')) returns contents of txtScannerClockFrequency as a double

strNewScannerClockFreq = get(hObject, 'String');
if isnan(str2double(strNewScannerClockFreq))
    hw = warndlg('You must specify a valid number!', ...
        'Invalid number', 'modal');
    uiwait(hw);
    strOldScannerClockFreq = get(hObject, 'UserData');
    set(hObject, 'String', strOldScannerClockFreq);
else
    set(hObject, 'UserData', strNewScannerClockFreq);
end

% --- Executes during object creation, after setting all properties.
function txtScannerClockFrequency_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtScannerClockFrequency (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in chkDisableSyncMarker.
function chkDisableSyncMarker_Callback(hObject, eventdata, handles)
% hObject    handle to chkDisableSyncMarker (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of chkDisableSyncMarker

% ATTENTION: it's DISABLE_SyncMarker!
checkBoxStatus = get(hObject, 'Value');
if checkBoxStatus == get(hObject, 'Max')
    set(handles.txtSyncMarkerUpdateInterval, 'Enable', 'off');
elseif checkBoxStatus == get(hObject, 'Min')
    set(handles.txtSyncMarkerUpdateInterval, 'Enable', 'on');
%     set(handles.txtSyncMarkerUpdateInterval, 'String', num2str(2));
end


function txtSyncMarkerUpdateInterval_Callback(hObject, eventdata, handles)
% hObject    handle to txtSyncMarkerUpdateInterval (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtSyncMarkerUpdateInterval as text
%        str2double(get(hObject,'String')) returns contents of txtSyncMarkerUpdateInterval as a double

strNewMarkerUpdateInterval = get(hObject, 'String');
if isnan(str2double(strNewMarkerUpdateInterval))
    hw = warndlg('You must specify a valid number!', ...
        'Invalid Number', 'modal');
    uiwait(hw);
    strOldMarkerUpdateInterval = get(hObject, 'UserData');
    set(hObject, 'String', strOldMarkerUpdateInterval);
else
    set(hObject, 'UserData', strNewMarkerUpdateInterval);
end


% --- Executes during object creation, after setting all properties.
function txtSyncMarkerUpdateInterval_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtSyncMarkerUpdateInterval (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function popNotchFilter_Callback(hObject, eventdata, handles)
% hObject    handle to popNotchFilter (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of popNotchFilter as text
%        str2double(get(hObject,'String')) returns contents of popNotchFilter as a double


% --- Executes during object creation, after setting all properties.
function popNotchFilter_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popNotchFilter (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function popLowCutoff_Callback(hObject, eventdata, handles)
% hObject    handle to popLowCutoff (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of popLowCutoff as text
%        str2double(get(hObject,'String')) returns contents of popLowCutoff as a double


% --- Executes during object creation, after setting all properties.
function popLowCutoff_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popLowCutoff (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


function txtStoragePath_Callback(hObject, eventdata, handles)
% hObject    handle to txtStoragePath (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtStoragePath as text
%        str2double(get(hObject,'String')) returns contents of txtStoragePath as a double

newFileStoragePath = get(hObject, 'String');
% Check whether the path is valid or not
if ~exist(newFileStoragePath, 'dir')
    hw = warndlg('You must specify a valid path!', 'Invalid Path', 'modal');
    uiwait(hw);
    originalFileStoragePath = get(hObject, 'UserData');
    set(hObject, 'String', originalFileStoragePath);
else
    set(hObject, 'UserData', newFileStoragePath);
end



% --- Executes during object creation, after setting all properties.
function txtStoragePath_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtStoragePath (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in btnStorage.
function btnStorage_Callback(hObject, eventdata, handles)
% hObject    handle to btnStorage (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

startPath = get(handles.txtStoragePath, 'UserData');
fileStoragePath = uigetdir(startPath, 'Choose the folder to store your eeg files');

if fileStoragePath ~= 0
set(handles.txtStoragePath, 'String', fileStoragePath);
set(handles.txtStoragePath, 'UserData', fileStoragePath);
end

function popHighCutoff_Callback(hObject, eventdata, handles)
% hObject    handle to popHighCutoff (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of popHighCutoff as text
%        str2double(get(hObject,'String')) returns contents of popHighCutoff as a double


% --- Executes during object creation, after setting all properties.
function popHighCutoff_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popHighCutoff (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in chkNotchFilter.
function chkNotchFilter_Callback(hObject, eventdata, handles)
% hObject    handle to chkNotchFilter (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of chkNotchFilter
checkBoxStatus = get(hObject, 'Value');
if checkBoxStatus == get(hObject, 'Max')
    set(handles.popNotchFilter, 'Enable', 'on');
elseif checkBoxStatus == get(hObject, 'Min')
    set(handles.popNotchFilter, 'Enable', 'off');
end

% --- Executes when selected object is changed in bpnTabPanel.
% Change the visible properties of the panels to simulate the tab page.
function bpnTabPanel_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in bpnTabPanel 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)

% Make the old frame invisible first
oldTab = get(eventdata.OldValue, 'Tag');
switch oldTab
    case 'tgbAmp'
        set(handles.pnlAmp, 'Visible','off');
    case 'tgbRecMon'
        set(handles.pnlRecMon, 'Visible','off');
    case 'tgbStorage'
        set(handles.pnlStorage, 'Visible','off');
    case 'tgbFilter'
        set(handles.pnlFilter, 'Visible','off');
    otherwise
        error 'Configuration: Non-exist Tab!';
end

% Make the new frame visilble
newTab = get(eventdata.NewValue, 'Tag');
switch newTab
    case 'tgbAmp'
        set(handles.pnlAmp, 'Visible','on');
    case 'tgbRecMon'
        set(handles.pnlRecMon, 'Visible','on');
    case 'tgbStorage'
        set(handles.pnlStorage, 'Visible','on');
    case 'tgbFilter'
        set(handles.pnlFilter, 'Visible','on');
    otherwise
        error 'Configuration: Non-exist Tab!';
end

% --- Executes on button press in btnOK.
function btnOK_Callback(hObject, eventdata, handles)
% hObject    handle to btnOK (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

configFilePath = handles.configFilePath;

% Check the validation status of user specified configuration
if isempty(get(handles.txtRealtimeWindowLength, 'String'))
    warndlg('You must specify the RealtimeWindowLength!', ...
        'Invalid Configuration!', 'modal');
    return;
end
if get(handles.chkEnableSyncBox, 'Value') == get(handles.chkEnableSyncBox, 'Max') ...
        && isempty(get(handles.txtScannerClockFrequency, 'String'))
    warndlg('You must specify the ScannerClockFrequency!', ...
        'Invalid Configuration!', 'modal');
    return;
end
if get(handles.chkDisableSyncMarker, 'Value') == get(handles.chkDisableSyncMarker, 'Min') ...
        && isempty(get(handles.txtSyncMarkerUpdateInterval, 'String'))
    warndlg('You must specify the SyncMarkerUpdateInterval!', ...
        'Invalid Configuration', 'modal');
    return;
end
if isempty(get(handles.txtStoragePath, 'String'))
   warndlg('You must specify the Storage Path!', ...
       'Invalid Configuration', 'modal');
   return;
end

saveconfig(configFilePath, hObject);

% close the config figure;
% NOTE: "close" will invoke the CloseRequestFcn to handle close the GUI,
% however "delete" directly delete the figure.
close(gcbf);


% --- Executes on button press in btnCancel.
function btnCancel_Callback(hObject, eventdata, handles)
% hObject    handle to btnCancel (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
close(gcbf);


% --- Executes when user attempts to close figConfig.
function figConfig_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figConfig (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

if isequal(get(hObject, 'waitstatus'), 'waiting')
    uiresume(hObject);
else
    delete(hObject);
end


% --- Executes when selected object is changed in pnlAmpConfig.
function pnlAmpConfig_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to the selected object in pnlAmpConfig 
% eventdata  structure with the following fields (see UIBUTTONGROUP)
%	EventName: string 'SelectionChanged' (read only)
%	OldValue: handle of the previously selected object or empty if none was selected
%	NewValue: handle of the currently selected object
% handles    structure with handles and user data (see GUIDATA)


function txtRealtimeWindowLength_Callback(hObject, eventdata, handles)
% hObject    handle to txtRealtimeWindowLength (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of txtRealtimeWindowLength as text
%        str2double(get(hObject,'String')) returns contents of txtRealtimeWindowLength as a double

strNewWindowLength = get(hObject, 'String');
if isnan(str2double(strNewWindowLength))
    hw = warndlg('You must specify a valid number!', ...
        'Invalid number', 'modal');
    uiwait(hw);
    strOldWindowLength = get(hObject, 'UserData');
    set(hObject, 'String', strOldWindowLength);
else
    set(hObject, 'UserData', strNewWindowLength);
end

% --- Executes during object creation, after setting all properties.
function txtRealtimeWindowLength_CreateFcn(hObject, eventdata, handles)
% hObject    handle to txtRealtimeWindowLength (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in chkEnableSyncBox.
function chkEnableSyncBox_Callback(hObject, eventdata, handles)
% hObject    handle to chkEnableSyncBox (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of chkEnableSyncBox
checkBoxStatus = get(hObject, 'Value');
if checkBoxStatus == get(hObject, 'Max')
    set(handles.txtScannerClockFrequency, 'Enable', 'on');
elseif checkBoxStatus == get(hObject, 'Min')
    set(handles.txtScannerClockFrequency, 'Enable', 'off');
end


% --- Executes on selection change in popBrainAmpNo.
function popBrainAmpNo_Callback(hObject, eventdata, handles)
% hObject    handle to popBrainAmpNo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns popBrainAmpNo contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popBrainAmpNo
contents = cellstr(get(hObject, 'String'));
allChannels = get(handles.tblChannelSelection, 'UserData');
if strcmp(contents{get(hObject, 'Value')}, '1')
    set(handles.tblChannelSelection, 'Data', allChannels(1:32, :));
elseif strcmp(contents{get(hObject, 'Value')}, '2')
    set(handles.tblChannelSelection, 'Data', allChannels);
    
end

% --- Executes during object creation, after setting all properties.
function popBrainAmpNo_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popBrainAmpNo (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end
